const express = require('express');
const app = express();
const fs = require('fs');
const jwt = require('jsonwebtoken');
const { expressjwt } = require("express-jwt");
const CryptoJS = require("crypto-js");
const ejs = require('ejs');

app.use(express.static('.'));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

async function render(file, data = {}) {
    try {
        //文件缓存
        let path = __dirname + '/view/' + file;
        let str = await fs.promises.readFile(path, { encoding: 'utf8' });
        let html = ejs.render(str, data);
        return html;
    } catch (err) {
        console.error(err);
        return '';
    }
}

// function getToken(req) {
//     if (req.headers.authorization && req.headers.authorization.split(" ")[0] === "Bearer") {
//         return req.headers.authorization.split(" ")[1];
//     } else if (req.query && req.query.token) {
//         return req.query.token;
//     }
//     return null;
// }
function getToken(req) {
    if (req.headers.authorization && req.headers.authorization.split(" ")[0] === "Bearer") {
        return CryptoJS.AES.decrypt(req.headers.authorization.split(" ")[1], secret).toString(CryptoJS.enc.Utf8);
    } else if (req.query && req.query.token) {
        return CryptoJS.AES.decrypt(req.query.token, secret).toString(CryptoJS.enc.Utf8);
    }
    return null;
}

let secret = 'Y%BG9GjXU:p^FaW~';

app.get('/', async function (req, res) {
    let token = jwt.sign({
        data: 'foobar'
    }, secret, { expiresIn: 3600 });

    token = CryptoJS.AES.encrypt(token, secret).toString();

    res.send(await render('index.html', { token }));
});

app.post('/test', function (req, res) {
    res.json({
        status: true,
        msg: 'ok',
        time: parseInt(new Date().getTime() / 1000),
    });
});


app.post('/api_two', expressjwt({ secret: secret, algorithms: ["HS256"], getToken: getToken }), async function (req, res) {

    res.json({
        status: true,
        msg: 'ok',
        decoded: req.auth,
    });
});



app.use(function (err, req, res, next) {
    if (err.name === "UnauthorizedError") {
        res.status(401).send("invalid token...");
    } else {
        next(err);
    }
});

app.listen(3000);
